import React from 'react';
import { isEqual } from 'lodash';
import {WeaErrorPage, WeaTools, WeaPopoverHrm, WeaLocaleProvider} from 'ecCom';
const getLabel = WeaLocaleProvider.getLabel;
//引入元素组件
import { Element } from './index';
class ElementIndie extends React.Component {
	constructor(props) {
        super(props);
        this.state = {
            config: null,
            eCss: '',
        }
        this.getElementData = this.getElementData.bind(this);
    }
    getElementData(params = {}){
        let url = params.elementtype == 'elementtemplate' ? '/api/portal/elementtemplate/preview':'/api/portal/elementindie/elementinfo';
        WeaTools.callApi(url, 'POST', params).then( data => {
            if(data.status === '2'){
                message.error(data.errormsg);
            }else{
                this.setState({
                    config: data.config,
                    eCss: data.eCss,
                });
            }
        });
    }
	componentWillMount(){
        this.getElementData(this.props.location.query);
	}
    componentWillReceiveProps(nextProps) {
        if(!isEqual(this.props.location.query, nextProps.location.query)){
            this.getElementData(nextProps.location.query);
        }
    }
    render() {
    	const { config, eCss } = this.state;
    	if(!config) return <div/>
    	let styleStr = "<style type='text/css'>" + eCss.replace(/\"/g, "") + "</style>";
        const { isSetting = false } = this.props.location.query;
        config.params = {...config.params, ...this.props.location.query};
        return <div>
            <div className='homepage' data-isSetting={isSetting}>
                <WeaPopoverHrm ecId={`${this && this.props && this.props.ecId || ''}_WeaPopoverHrm@r3x0uf`}/>
                <div dangerouslySetInnerHTML = {{__html:styleStr}}></div>
                <Element ecId={`${this && this.props && this.props.ecId || ''}_Element@8du67c`} config={{...config, isSetting}}/>
            </div>
        </div>
    }
}
class MyErrorHandler extends React.Component {
    render() {
        const hasErrorMsg = this.props.error && this.props.error !== "";
        return ( <WeaErrorPage ecId={`${this && this.props && this.props.ecId || ''}_WeaErrorPage@10fabz`} msg = { hasErrorMsg ? this.props.error :getLabel(385218,"对不起，该页面异常，请联系管理员！") }/>
        );
    }
}
ElementIndie = WeaTools.tryCatch(React, MyErrorHandler, { error: "" })(ElementIndie);
export default ElementIndie;
